<?php
declare(strict_types=1);

namespace ServerApp\lib\server\delay_push;

use ServerApp\lib\process\SGlobal;
use ServerApp\lib\process\SPRunnable;
use Swoole\Process;

/**
 * Class Task
 * @package txz\client\push\server
 */
class Task implements SPRunnable
{
    private $func;
    public function __construct(IDelayPush $func2)
    {
        $this->func = $func2;
    }

    /**
     * @param Process $process
     * @return mixed|void
     */
    public function run(Process $process): void
    {
        swoole_event_add(SGlobal::getInstance()->process->pipe, function (){
            $key = SGlobal::getInstance()->process->read();
            if ($key){
                $str = file_get_contents($key);
                tracker(I, "process:".SGlobal::getInstance()->process->pid." get messages, now sending");
                $rows = json_decode($str, true);
                $arr = [];
                foreach ($rows as $message) {
                    $res = $this->func->push_info($message);
                    if ($res) {
                        $arr[] = $res;
                    }
                }

                $this->func->end_push($arr);
                SGlobal::getInstance()->process->write(SGlobal::getInstance()->process->pid.'');
            }
        });
    }
}
